import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewLogic extends GetxController {
  final title = ''.obs;
  late final WebViewController webController;

  Future<bool> canBack() async {
    var isFinish = await webController.canGoBack().then((value){
      if(value){
        webController.goBack();
      }
      return !value;
    });
    return isFinish;
  }

  @override
  void onInit() {
    super.onInit();
    webController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) async {
            title.value = (await webController.getTitle()) ?? '';
          },
          onPageFinished: (String url) {},
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              return NavigationDecision.prevent; //阻止
            }
            return NavigationDecision.navigate;
          },
        ),
      );
  }

  @override
  void onReady() {
    webController.loadRequest(Uri.parse(Get.arguments['url']));
    super.onReady();
  }
}
